import socket from '@/socket'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  connected: false,    // 连接状态
  nickname: '',
  nicknames: [],   // 房间用户列表
  holder: '',   // 游戏主持
  lines: []   // 房间的绘图信息
}

const mutations = {
  updateNickname(state, nickname) {
    state.nickname = nickname || ''
  },
  updateNicknames(state, nicknames) {
    state.nicknames = nicknames || []
  },
  updateHolder(state, holder) {
    state.holder = holder || ''
  },
  updateLines(state, lines) {
    state.lines = lines || []
  },
  addToNicknames(state, nickname) {
    if (state.nicknames.includes(nickname)) {
      state.nicknames.push(nickname)
    }
  },
  updateConnected(state, flag) {
    state.connected = flag
  },
  // 画新线
  drawNewLine(state, newLine) {
    state.lines.push(newLine)
  },
  updateNewLine(state, lastLine) {
    const line = state.lines.at(-1)
    line.points = lastLine.points
  },
  delFromNicknames(state, nickname) {
    state.nicknames = state.nicknames.filter(item => item !== nickname)
  }
}

const actions = {
  checkUserExist(context, nickname) {
    return new Promise((res, rej) => {
      socket.emit('check_user_exist', nickname, isExist => {
        res(isExist)
      })
    })
  },
  sendUserEnter(context) {
    const nickname = localStorage.getItem('nickname')
    // 发送消息
    socket.emit('enter', nickname)
    // 进入房间，将nickname放入state
    context.commit('updateNickname', nickname)
  },
  sendStartGame(context, answer) {
    // 发消息，通知到服务器
    socket.emit('start_game', answer)
  },
  // 终止游戏 - 发消息
  sendStopGame(context) {
    socket.emit('stop_game')
  },
  sendDrawNewLine(context, line) {
    socket.emit('new_line', line)
  },
  sendUpdateDrawNewLine(context, line) {
    socket.emit('update_line', line)
  },
  sendAnswerGame(context, inputImageName) {
    socket.emit('answer_game', inputImageName)
  },
  sendUserLeave(context) {
    // 发送我们退出的消息
    socket.emit('leave')
    // 重置本地昵称
    context.commit('updateNickname', '')
    localStorage.removeItem('nickname')
  }
}

const getters = {
  isGameStarted() {
    return !!state.holder
  },
  isGameHolder(state) {
    return state.nickname === state.holder
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
